package com.lpb.spring.lpbspring.getway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lpb.spring.lpbspring.getway.model.Response;
import com.lpb.spring.lpbspring.getway.model.RestModel;
import com.lpb.spring.lpbspring.getway.rtc.TrtcRecordUsageVo;
import com.lpb.spring.lpbspring.getway.rtc.TrtcUsageVo;
import com.lpb.spring.lpbspring.getway.rtc.enums.EnumServiceSpecification;
import com.lpb.spring.lpbspring.getway.util.DateUtils;
import com.lpb.spring.lpbspring.getway.util.Md5;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName Test
 * @Description TODO
 * @date 2022/12/23 00:06
 * @Version 1.0
 * @authoe linpengbo
 */
public class Test {

    private static final String pkey="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIFdlRKrnYSpTasqYXQpd/X5AFzKwjR5C0Xx8TEO5w0KgtU5Jz0YiIPThkrxKFRG5HspFaN1j4xinNMID1XDGH9VbxcCQNHgmv5pyFYrNh5lIGLaWCD25aWm8bbwkpxoaTsU/fl9xR8KpElnmQl9WZaTZkHYWest+ByeCo6Fz7bzAgMBAAECgYADMh+jpW+vvkr35oUfzIJ1JiCXKj8f8rmPkcmGj7qvfMn8oHvSq497yjbwFQMNCe9NB5fMQPQ54JnFMNbIJJivSykwCviE6/BFJorJjF1aUxnXSFlTcaRLdkb9B5d6WXnAN8UWYfWfq0Tos1IXsXLogNWnbuhILjilCdaSUA/u6QJBAPlS43Y8QKMKtGGqGR9qmx3RhS0jIGrjYsq2tKZysjvQagSf7ANn9JHXv2Wqm8LCrYr8Bl2jhbUseN0ioXxs8lUCQQCE1GGxj+PdthD6sANOskMq0eN/QV5Ri36yuzKVT4TTPfHe/CacrOsU7rLES+Bwprrm3kBzU2Xd3P33C6NAX5wnAkBdxNbXeQG2UChXMuoP7sA4DrzPpQ5kJPDa3KxEjY6LAG9fHeZdwZMx5rqNOgUq0p0CUJb0ULPQ19D9GjEx4qehAkBuTD1jSGya6lhnEklsy7HimK8kOI+tfvwSRkfWnFVbZBC4bQFTEHOUyjE/txID+S8yDlPOb+4isSNiRROmnL35AkAQtDHZrJp13ux6ywp71cDqjG4aiybjwGQeDNzA7PPDxxcXY7w/TgYzbkkLORiUzcd2GFT01QiHOUZWY9v78Wyx";
    private static final String secret = "test.train-054f969771ad4257ad33f52c66a7b8be";
    private static final String appSdkId = "1";
    /**
     * @return {"data":{"expireTime":863871,"authToken":"6bccd31c-fa1f-46ac-8a59-8681085dbe9f","userMappingId":20137115,"tenantUserId":33234},"success":true}
     * tenant（int） 对应值 1,
     *          userTenant（int）对应值 1
     *          tenantUserId（long）
     *          timestamp（long）
     *          signature（string）
     */
    private static RestModel getToken() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("userTenant","1");
        data.put("tenantUserId","33234");
        data.put("timestamp",String.valueOf(System.currentTimeMillis()));
        try {
            Date date = new Date();
            Long time = date.getTime() / 1000 / 1000;
            String signature = Md5.getMD5(time + appSdkId + secret);
            //String sign = RSAUtils.sign(WebUtils.map2querystring0(new TreeMap<>(data)).getBytes(StandardCharsets.UTF_8), pkey);
            data.put("signature", signature);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        String response = OpenGwHttpUtil.getInstance().post("/security/get-auth-token", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }

    /**
     * "tenant": 1, //1是才测业务线
     *   "taskName": "才测考试测试任务",
     *   "taskType": 3,  //任务类型：3-视频通话
     *   "needRecord": 1,  //1-需要录制
     *   "startTime": "20221129203649",
     *   "endTime": "20221129213649",
     *   "serviceSupplier": 1,  //1-腾讯
     *   "rtcRecordingCfgInfoDtoList": [
     *     {
     *       "rtcRecordingMode": 1 //1-成员分别独立录制
     *     }
     * @return  {"data":158811,"success":true}
     * @throws Exception
     */
    private static RestModel createVideoTask() throws Exception {
        Map<String, Object> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("taskName","测试");
        data.put("taskType","3");
        data.put("needRecord","1");
        data.put("startTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
        data.put("endTime", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
        data.put("serviceSupplier","1");
        data.put("timestamp",String.valueOf(System.currentTimeMillis()));
        String response = OpenGwHttpUtil.getInstance().postJson("/video-task/create-video-task", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }

    /**
     * {"data":[{"duration":707,"fileName":"T158513_M14945","createtime":"20221213103119","videoUrl":"https://1500001382.vod2.myqcloud.com/6c980af6vodcq1500001382/77cf5a13243791577181600557/playlist.m3u8?t=64927455&us=WUTJfTSrzp&sign=d4b549a309034b10739b787552ca50ed","fileSize":16975515,"kind":0,"transcodeInfoList":[],"tenantUserId":14105,"streamName":"09465d420a6ed41bd2966036da5851ac","taskId":158513,"fileFormat":"m3u8","fileId":"243791577181600557"},{"duration":5,"fileName":"T158513_M14945","createtime":"20221213103616","videoUrl":"https://1500001382.vod2.myqcloud.com/6c980af6vodcq1500001382/6ea108ed243791577181224144/playlist.m3u8?t=64927455&us=TpaLEvz4Bp&sign=14562ef93830cc4c7d8051034d3a2acd","fileSize":647803,"kind":0,"transcodeInfoList":[],"tenantUserId":14105,"streamName":"09465d420a6ed41bd2966036da5851ac","taskId":158513,"fileFormat":"m3u8","fileId":"243791577181224144"}],"success":true}
     * @return
     * @throws Exception
     */
    private static RestModel listVideoRecordList() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("taskId","158513");
        data.put("timestamp",String.valueOf(System.currentTimeMillis()));
        String response = OpenGwHttpUtil.getInstance().post("/video-task/list-task-video-records", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }


    /**
     * @return {"success":true}
     * @throws Exception
     */
    private static RestModel transcode() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("fileId","5285890804928533225");
        data.put("transcodeModel","1");
        String response = OpenGwHttpUtil.getInstance().post("/video-task/transcode-video-record", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }

    //---------用量获取接口

    /**获取TRTC订阅时长
     * @return {"success":true}
     * @throws Exception
     */
    private static RestModel trtc() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("startDate","20230227");
        data.put("endDate","20230227");
        data.put("granularity","20230227");
        data.put("startTime","20230227");
        data.put("endTime","20230227");
        String response = OpenGwHttpUtil.getInstance().post("/video-usage/get-trtc-usage", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }


    /**获取云端录制时长
     * @return {"success":true}
     * @throws Exception
     */
    private static RestModel ydlz() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("startDate","20230228");
        data.put("endDate","20230228");
        String response = OpenGwHttpUtil.getInstance().post("/video-usage/get-recording-usage", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }


    /**获取点播流量
     * @return {"success":true}
     * @throws Exception
     */
    private static RestModel voddb() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("startDate","20230227");
        data.put("endDate","20230227");
        String response = OpenGwHttpUtil.getInstance().post("/video-usage/get-vod-flow-usage", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }

    /**获取点播存储
     * @return {"success":true}
     * @throws Exception
     */
    private static RestModel voddbcc() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("granularity","2");
        data.put("startTime","20230228120000");
        data.put("endTime","20230228130000");
        String response = OpenGwHttpUtil.getInstance().post("/video-usage/get-vod-storage-usage", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }


    /**
     * @return 获取点播转码时长
     * @throws Exception
     */
    private static RestModel transc() throws Exception {
        Map<String, String> data = new HashMap<>(5);
        data.put("tenant","1");
        data.put("granularity","1");
        data.put("startTime","20230227000000");
        data.put("endTime","20230228000000");
        String response = OpenGwHttpUtil.getInstance().post("/video-usage/get-vod-transcoding-usage", data);
        System.out.println(response);
        return JSON.parseObject(response, Response.class).asModel();
    }





  //Authorization= app key="69cb9f273cd3fbe9c82b7d925b5a2b3f", algorithm="HmacSHA256", headers="x-alt-timestamp accept", signature="8LeqOYOUgeVQr7XXoAxETN_1gH3OHB5pYybFWBF1THU="
    public static void main(String[] args) {
        try {
//            RestModel token = ydlz();
//            TrtcRecordUsageVo trtcRecordUsageVo = JSONObject.parseObject(token.getData().toString(), TrtcRecordUsageVo.class);
//            Map<EnumServiceSpecification, Long> enumServiceSpecificationLongMap = TrtcRecordUsageVo.filterUsageByTimeInterval("2023022810", trtcRecordUsageVo);
//            System.out.println(JSON.toJSONString(enumServiceSpecificationLongMap));
//            System.out.println(formatAgeByBirthDay("1994-11-16","yyyy-MM-dd")+"岁");
//            RestModel trtc = trtc();
//            System.out.println("asd="+JSONObject.toJSONString(trtc.getData()));
//            System.out.println(Integer.parseInt("2021020301".substring(8,10)));
            System.out.println(1024 * 1024 * 1024);
            Double s=10737418.0;
            Double netFileSizeDescription = getNetFileSizeDescription(s);
            System.out.println(netFileSizeDescription);
            System.out.println(netFileSizeDescription.equals(0.0));
            String ss="元/分钟";
            System.out.println(ss.split("/")[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Double getNetFileSizeDescription(Double size) {
        DecimalFormat format = new DecimalFormat("###.0");
        double i=0;
        if (size >= 1024 * 1024 * 1024) {
             i = (size / (1024.0 * 1024.0 * 1024.0));
        }
        return Double.parseDouble(format.format(i));
    }



    /**
     * 计算详细年龄，精确到秒
     * @param birth
     * @return
     */
    public static String  getDetailedAge(String birth) throws Exception{
        String[] parsePatterns = {"yyyy-MM-dd HH:mm:ss"};
        Date date = DateUtils.parseDate(birth, parsePatterns);
        if(date.after(new Date())){
            return "err";
        }
        String s =  DurationFormatUtils.formatPeriod(date.getTime(), new Date().getTime(),   "yyyy-MM-dd HH:mm:ss");
        return s;
    }

    /**
     * 计算详细年龄，精确到秒
     * @param birth
     * @return
     */
    public static String  getDetailedAge(Date birth) throws Exception {
        String s =  DurationFormatUtils.formatPeriod(birth.getTime(), new Date().getTime(),   "yyyy-MM-dd HH:mm:ss");
        return s;
    }



    /**
     * 计算年龄，返回年龄和年龄单位的可精确到秒
     * @param birth
     * @return
     */
    public static Map<String,String> formatAge(Date birth) throws Exception{
        if(birth==null){
            return null;
        }
        String age=getDetailedAge(birth);
        String[] ages=age.split(" ");
        String[] ymd=ages[0].split("-");
        String[] hms=ages[1].split(":");
        Map<String, String> m=new LinkedHashMap<String, String>();
        m.put("y",ymd[0]);
        m.put("m",ymd[1]);
        m.put("d",ymd[2]);
        m.put("h",hms[0]);
        m.put("n",hms[1]);
        m.put("s",hms[2]);
        return m;
    }

    public static Integer formatAgeByBirthDay(String birth,String parsePattern) throws Exception{
        if(StringUtils.isBlank(birth)||StringUtils.isBlank(parsePattern)){
            return null;
        }
        String[] parsePatterns = {parsePattern};
        Date date = DateUtils.parseDate(birth, parsePatterns);
        return formatAgeByBirthDay(date);
    }

    public static Integer formatAgeByBirthDay(Date birthDay) throws Exception{
        if(birthDay==null){
            return null;
        }
        Map<String, String> stringStringMap = formatAge(birthDay);
        if(MapUtils.isEmpty(stringStringMap)){
            return null;
        }
        return stringStringMap.get("y")==null?null:Integer.parseInt(stringStringMap.get("y"));
    }


}
